<?php


/**
 *  将一个用户自定义时区的日期转为GMT时间戳
 *
 * @access  public
 * @param   string      $str
 *
 * @return  integer
 */
function local_strtotime($str){
	
    $timezone 	= 	isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];
    /**
    * $time = mktime($hour, $minute, $second, $month, $day, $year) - date('Z') + (date('Z') - $timezone * 3600)
    * 先用mktime生成时间戳，再减去date('Z')转换为GMT时间，然后修正为用户自定义时间。以下是化简后结果
    **/
    $time = strtotime($str) - $timezone * 3600;
    return $time;
}

/**
 * 根据过滤条件获得排序的标记
 *
 * @access  public
 * @param   array   $filter
 * @return  array
 */
function sort_flag($filter){
    $flag['tag']    = 'sort_' . preg_replace('/^.*\./', '', $filter['sort_by']);
    $flag['img']    = '<img src="' . __PUBLIC__ . '/Image/Admin/' . ($filter['sort_order'] == "DESC" ? 'sort_desc.gif' : 'sort_asc.gif') . '"/>';

    return $flag;
}


/**
 * 将GMT时间戳格式化为用户自定义时区日期
 *
 * @param  string       $format
 * @param  integer      $time       该参数必须是一个GMT的时间戳
 *
 * @return  string
 */
function local_date($format, $time = NULL){
    if ($time === NULL){
        $time = gmtime();
    }
    elseif ($time <= 0){
        return '';
    }
    return date($format, $time);
}

/**
 * 记录管理员的操作内容
 *
 * @access  public
 * @param   string      $sn         数据的唯一值
 * @param   string      $action     操作的类型
 * @param   string      $content    操作的内容
 * @return  void
 */
function admin_log($sn = '', $action, $content){
    ///$log_info = $GLOBALS['_LANG']['log_action'][$action] . $GLOBALS['_LANG']['log_action'][$content] .': '. addslashes($sn);
    $log_info 	= 	$action . $content .': '. addslashes($sn);
    $sql 		= 	'INSERT INTO ' . 'ybr_admin_log' . ' (log_time, user_id, log_info, ip_address) ' .
            		" VALUES ('" . gmtime() . "', $_SESSION[admin_id], '" . stripslashes($log_info) . "', '" . real_ip() . "')";
    M()->query($sql);
}

/**
 * 得到新订单号
 * @return  string
 * 
 */
function get_order_sn(){
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);    
    return date('ymd') . substr(time(),-4) . substr(microtime(),3,6) . sprintf('%02d', rand(0, 99)); // 并发量支持1/1000000
}

/**
 * 格式化商品价格
 *
 * @access  public
 * @param   float   $price  商品价格
 * @return  string
 * 
 */
function price_format($price, $change_price = true){
    if($price===''){
     	$price			=	0;
    }
    if ($change_price){
        switch (5){
            case 0:
                $price 	= 	number_format($price, 2, '.', '');
                break;
            case 1: // 保留不为 0 的尾数
                $price 	= 	preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\1\2\3', number_format($price, 2, '.', ''));

                if (substr($price, -1) == '.'){
                    $price 	= 	substr($price, 0, -1);
                }
                break;
            case 2: // 不四舍五入，保留1位
                $price 	= 	substr(number_format($price, 2, '.', ''), 0, -1);
                break;
            case 3: // 直接取整
                $price 	= 	intval($price);
                break;
            case 4: // 四舍五入，保留 1 位
                $price 	= 	number_format($price, 1, '.', '');
                break;
            case 5: // 先四舍五入，不保留小数
                $price 	= 	round($price);
                break;
        }
    }
    else{
        $price 			= 	number_format($price, 2, '.', '');
    }
    //return sprintf($GLOBALS['_CFG']['currency_format'], $price);
    return $price;
}

/**
 * 获得指定分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 * @return  string
 */
function get_children($cat = 0){
    return 'g.cat_id ' . db_create_in(array_unique(array_merge(array($cat), array_keys(cat_list($cat, 0, false)))));
}

/**
 * 商品分类
 * Enter description here ...
 * @param $cat_id
 */
function cat_list($cat_id = 0){
	static $res = NULL;

	if ($res === NULL){
			
		$sql = 	" SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children "
				." FROM ybr_category  AS c "
				." LEFT JOIN  ybr_category  AS s ON s.parent_id=c.cat_id "
				." GROUP BY c.cat_id "
				." ORDER BY c.parent_id, c.sort_order ASC ";
		//$res = $GLOBALS['db']->getAll($sql); 
		// 最好是可以缓存起来，不用每次都到数据库取           
		$res	=	M()->query($sql);             

		$sql = "SELECT cat_id, COUNT(*) AS goods_num " .
				" FROM " . 'ybr_goods' .
				" WHERE is_delete = 0 AND is_on_sale = 1 " .
				" GROUP BY cat_id";
		//$res2 = $GLOBALS['db']->getAll($sql);
		$res2	=	M()->query($sql);			
		
		$sql = "SELECT gc.cat_id, COUNT(*) AS goods_num " .
				" FROM " . 'ybr_goods_cat' . " AS gc , " . 'ybr_goods' . " AS g " .
				" WHERE g.goods_id = gc.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 " .
				" GROUP BY gc.cat_id";
		//$res3 = $GLOBALS['db']->getAll($sql);
		$res3	=	M()->query($sql);
		//echo $sql;	    
		
		$newres = array();
		foreach($res2 as $k=>$v){
			$newres[$v['cat_id']] = $v['goods_num'];
			foreach($res3 as $ks=>$vs){
				if($v['cat_id'] == $vs['cat_id']){
				$newres[$v['cat_id']] = $v['goods_num'] + $vs['goods_num'];
				}
			}
		}
		foreach($res as $k=>$v){
			$res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0;
		}            
	}
	if (empty($res) == true){
		return $re_type ? '' : array();
	}
	$options 		= 	cat_options($cat_id, $res); // 获得指定分类下的子分类的数组
	return $options;
}


/**
 * 过滤和排序所有分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */
function cat_options($spec_cat_id, $arr){
	static $cat_options = array();
	// 递归算法:最简单使用
	// $cat_options	=	$this->catsort($arr,0,0);
	$options			=	catsort($arr,0,0);
	$cat_options[0] 	= 	$options;	
	// cat_id 为0,直接返回数组,否则找到指定cat_id下的
	if (!$spec_cat_id){
		return $options;
	}
	else{
		if (empty($options[$spec_cat_id])){
			return array();
		}

		$spec_cat_id_level = $options[$spec_cat_id]['level'];

		foreach ($options AS $key => $value){
			if ($key != $spec_cat_id){
				unset($options[$key]);
			}
			else{
				break;
			}
		}

		$spec_cat_id_array = array();
		foreach ($options AS $key => $value){
			if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) || ($spec_cat_id_level > $value['level'])){
				break;
			}
			else{
				$spec_cat_id_array[$key] = $value;
			}
		}
		$cat_options[$spec_cat_id] = $spec_cat_id_array;
		return $spec_cat_id_array;
	}
}
	
/**
 * 自动返回表名字,兼容带有前缀的,自动去除前缀
 * @param	$tableName 
 * @example	order_info
 * @return	OrderInfo
 * 
 */
function auto_table_name($table){
	/*判断是否存在前缀*/
	$is_exsist_prefix	=	strstr($table,"ybr_"); 
	if($is_exsist_prefix){
		$table			=	str_replace('ybr_', '', $table);
	}
		
	$table_name_array	=	explode("_", $table);
	$tableName			=	'';
	if(count($table_name_array) > 1){
		foreach($table_name_array as $name){
			$tableName 	.=	ucwords($name);
		}
	}else{
		$tableName	=	ucwords( $table_name_array[0]);
	}
	return $tableName;
}



